package com.haierp.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;

import com.haierp.enums.OrderStatus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.haierp.enums.GeneralStatus;
import com.haierp.enums.InoutOperatorType;
import com.haierp.exception.ErpCommonException;
import com.haierp.exception.InventoryException;
import com.haierp.mapper.InventoryAreaMapper;
import com.haierp.mapper.PurchaseStorageDetailMapper;
import com.haierp.model.ErpOrder;
import com.haierp.model.Inventory;
import com.haierp.model.InventoryArea;
import com.haierp.model.InventoryOut;
import com.haierp.model.InventoryOutDetail;
import com.haierp.model.InventoryRecord;
import com.haierp.model.InventoryStock;
import com.haierp.model.ItemSku;
import com.haierp.model.ShippingOrder;
import com.haierp.model.authority.UserHai;
import com.haierp.model.purchase.PurchaseStorageDetail;
import com.haierp.service.IErpOrderService;
import com.haierp.service.IInventoryAreaService;
import com.haierp.service.IInventoryInoutService;
import com.haierp.service.IInventoryOutService;
import com.haierp.service.IInventoryRecordService;
import com.haierp.service.IInventoryService;
import com.haierp.service.IInventoryStockService;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.IWarehouseService;
import com.haierp.service.authority.IUserServiceHai;
import com.haierp.service.purchase.IPurchaseStorageDetailService;
import com.haierp.service.purchase.IPurchaseStorageService;
import com.haierp.util.DateUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.util.Underline2Camel;
import com.haierp.util.ExcelTool.ExcelHelper;
import com.haierp.vo.InventoryInoutVO;
import com.haierp.vo.InventoryOutVO;
import com.haierp.vo.InventoryQueryVO;
import com.haierp.vo.json.PicModel;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.BeanUtils;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

/**
 * 库存处理器
 * 
 * @author liuhui
 *
 */
@Controller
@RequestMapping("/inventory")
public class InventoryController extends BaseController {
	@Autowired
	private IInventoryService inventoryService;
	@Autowired
	private IInventoryAreaService inventoryAreaService;
	@Autowired
	private IInventoryRecordService inventoryRecordService;
	@Autowired
	private IInventoryInoutService inventoryInoutService;
	@Autowired
	private IWarehouseService warehouseService;
	@Autowired
	private IInventoryOutService inventoryOutService;
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	@Autowired
	private IErpOrderService erpOrderService;
	@Autowired
	private IInventoryStockService inventoryStockService;
	@Autowired
	private InventoryAreaMapper inventoryAreaMapper;
	@Autowired
	private IUserServiceHai userServiceHai;
	@Autowired
	private PurchaseStorageDetailMapper purchaseStorageDetailMapper;
	@Autowired
	private IItemSkuService itemSkuService;
	
	@Autowired
	private IPurchaseStorageDetailService purchaseStorageDetailService;

	
	@RequestMapping("/query")
	@ResponseBody
	public Object query(Long itemId, Long skuId) {
		if (skuId != null) {
			Inventory inventory = inventoryService.queryInventoryBySkuId(itemId, skuId);
			return JsonResult.buildSuccess(inventory);
		} else {
			return JsonResult.buildFailed("没有SKU id");
		}
	}

	@RequestMapping("/area/queryList")
	@ResponseBody
	public Object queryInventoryAreas(InventoryQueryVO inventoryQueryVO) {
		JsonPageResult<List<InventoryArea>> result = new JsonPageResult<>();
		try {
			if(StringUtil.isNotBlank(inventoryQueryVO.getOrderBy())) {
				if(inventoryQueryVO.getOrderBy().equals("totalAvailableInv")){
					inventoryQueryVO.setOrderBy("orderNumber");
				}
				String orderBy = Underline2Camel.camel2Underline(inventoryQueryVO.getOrderBy());
				inventoryQueryVO.setOrderBy(orderBy);
			}
			result = inventoryAreaService.queryInventoryAreas(inventoryQueryVO);
			result.buildIsSuccess(true);
			ShiroUser shiroUser = this.getShiroUser();
			Set<String> roles = shiroUser.getRoles();
			if(roles.contains("irhdaili")){
				result.setAgentRoler(true);
			}
			if(roles.contains("noexport")) {
				result.setNoEexportRoler(true);
			}
		} catch (Exception e) {
			result.buildIsSuccess(false);
		}
		return result;
	}

	@RequestMapping("/area/transTo")
	@ResponseBody
	public Object transToInventory(Long inventoryAreaId, int toTrans, String positionNo,Long storageDetailId,String upc) {
		if (inventoryAreaId == null) {
			return JsonResult.buildFailed("没有inventoryArea id");
		}
		if(toTrans<=0){
			return JsonResult.buildFailed("在途到仓必须为正数");
		}
		if(storageDetailId != null) {
			PurchaseStorageDetail one = purchaseStorageDetailMapper.selectById(storageDetailId);
			if (one.getOnlineQuantity() < toTrans) {
				return JsonResult.buildFailed("入库数超过该网购单的在途数量，该网购单号实际在途为："+ one.getOnlineQuantity());
			}
		}
		try {
			inventoryService.transToInventory(inventoryAreaId, toTrans, positionNo, storageDetailId);

			if (StringUtils.isNotBlank(upc)) {
				InventoryArea inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
				if (!upc.equals(inventoryArea.getUpc())) {
					ItemSku itemSku = itemSkuService.selectById(inventoryArea.getSkuId());
					EntityWrapper<InventoryArea> entityWrapperOne = new EntityWrapper<>();
					entityWrapperOne.where("sku_id={0}", inventoryArea.getSkuId());
					List<InventoryArea> inventoryAreaList = inventoryAreaService.selectList(entityWrapperOne);
					for (InventoryArea inventoryArea2 : inventoryAreaList) {
						inventoryArea2.setUpc(upc);
						inventoryAreaService.updateSelectiveById(inventoryArea2);
					}
					EntityWrapper<ErpOrder> erpList = new EntityWrapper<>();
					erpList.where("sku_id={0}", inventoryArea.getSkuId());
					List<ErpOrder> erpAreaList = erpOrderService.selectList(erpList);
					for (ErpOrder erpOrder : erpAreaList) {
						erpOrder.setUpc(upc);
						erpOrderService.updateSelectiveById(erpOrder);
					}
					itemSku.setUpc(upc);
					itemSkuService.updateSelectiveById(itemSku);
				}

			}
		} catch (InventoryException e) {
			return JsonResult.buildFailed("在途入仓失败！错误：" + e.getMessage());
		}
		
		//对子订单进行库存分配
		InventoryArea inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
		try {
			erpOrderService.lockErpOrderBySkuId(inventoryArea.getSkuId());
		} catch (InventoryException e) {
			logger.info("在途入库，子订单重新库存分配异常skuid:"+inventoryArea.getSkuId(), e);
		}
		return JsonResult.buildSuccess(null);
	}

	// ------------test------------------------
	// http://localhost:8080/haierp1/inventory/add?itemId=73&skuId=352&warehouseId=16&positionNo=S001&inventory=10&transInv=5

	@RequestMapping("/add")
	@ResponseBody
	public Object add(Long itemId, Long skuId, Long warehouseId, String positionNo, Integer inventory,
			Integer transInv) {
		InventoryArea inventoryArea = new InventoryArea();
		inventoryArea.setItemId(itemId);
		// inventoryArea.setItemName("test");
		inventoryArea.setSkuId(skuId);
		// inventoryArea.setSkuCode("testskuCode");
		// inventoryArea.setSkuPic(skuPic);
		// inventoryArea.setUpc(upc);
		inventoryArea.setInventory(inventory);
		inventoryArea.setTransInv(transInv);
		inventoryArea.setWarehouseId(warehouseId);
		// inventoryArea.setWarehouseName(warehouseName);
		inventoryArea.setPositionNo(positionNo);
		inventoryArea.setGmtCreate(new Date());
		inventoryArea.setGmtModify(new Date());
		inventoryAreaService.addInventoryArea(inventoryArea,InoutOperatorType.PURCHASE_IN,"采购进入库存");
		return JsonResult.buildSuccess(null);

	}

	@RequestMapping("/lock")
	@ResponseBody
	public Object lockOrder(Long orderId) throws InventoryException {
		ErpOrder order = erpOrderService.selectById(orderId);
		return JsonResult.buildSuccess(inventoryService.lockedInventroyErpOrder(order));
	}

	@RequestMapping("/release")
	@ResponseBody
	public Object releaseOrder(Long orderId) throws InventoryException {
		ErpOrder order = erpOrderService.selectById(orderId);
		return JsonResult.buildSuccess(inventoryService.releaseInventory(order));
	}

	@RequestMapping("/send")
	@ResponseBody
	public Object sendOrder(Long orderId) throws InventoryException {
		ErpOrder order = erpOrderService.selectById(orderId);
		inventoryService.sendInventroyOrder(order);
		return JsonResult.buildSuccess(null);
	}

	/**
	 * 库存调整，库存盘进、盘出
	 * 
	 * @param orderId
	 * @return
	 * @throws InventoryException
	 */
	@RequestMapping("/inventoryCheckIn")
	@ResponseBody
	public Object inventoryCheckIn(Long skuId, Long warehouseId, String positionNo, Integer quantity, String inoutReason)
			throws InventoryException {
		// 非空校验
		if (skuId == null || warehouseId == null || StringUtils.isBlank(positionNo) || quantity == null || StringUtils.isBlank(inoutReason)) {
			return JsonResult.buildFailed("有空数据");
		} else {
			if (quantity <= 0) {
				return	JsonResult.buildFailed("增加库存要为正数");
			}
			try {
				inventoryAreaService.inventoryCheckIn(skuId, warehouseId, positionNo,quantity,inoutReason);
			} catch (ErpCommonException e) {
				this.logger.error(e);
				return JsonResult.buildFailed(e.getErrorMsg());
			} catch (Exception ex) {
				this.logger.error(ex);
				return JsonResult.buildFailed("未知异常");
			}
			try {
				//对子订单进行库存分配
				erpOrderService.lockErpOrderBySkuId(skuId);
			} catch (InventoryException e) {
				logger.info("库存盘进，子订单重新库存分配异常skuid:"+skuId, e);
			}

		}
		return JsonResult.buildSuccess(null);
	}
    /**
     * 库存盘出
     * @param inventoryAreaId
     * @param quantity
     * @return
     * @throws InventoryException
     */
	@RequestMapping("/inventoryCheckOut")
	@ResponseBody
	public Object inventoryCheckOut(Long inventoryAreaId, Integer quantity, String inoutReason) throws InventoryException {
		// 非空校验
		if (inventoryAreaId== null ||quantity == null) {
			return JsonResult.buildFailed("有空数据");
		}else{
			if (quantity <= 0) {
				return JsonResult.buildFailed("减少的库存要为正数");
			}
			try {
				inventoryService.inventoryCheckOut(inventoryAreaId, quantity, inoutReason);
			}catch (InventoryException e) {
				this.logger.error(e);
				return JsonResult.buildFailed(e.getMessage());
			} catch (Exception ex) {
				this.logger.error(ex);
				return JsonResult.buildFailed("未知异常");
			}
			
			//对子订单进行库存分配
			InventoryArea inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
			try {
				erpOrderService.lockErpOrderBySkuId(inventoryArea.getSkuId());
			} catch (InventoryException e) {
				logger.info("库存盘出，子订单重新库存分配异常skuid:"+inventoryArea.getSkuId(), e);
			}
		}
		return JsonResult.buildSuccess(null);
	}
	
	@RequestMapping("/record/queryList")
	@ResponseBody
	public Object queryInventoryRecords(Long id) {
		JsonPageResult<List<InventoryRecord>> result = new JsonPageResult<>();
		try {
			List<InventoryRecord> inventoryRecordList =  inventoryRecordService.queryByErpOrderId(id);
			result.setData(inventoryRecordList);
			result.buildIsSuccess(true);
		} catch (Exception e) {
			result.buildIsSuccess(false);
		}
		return result;
	}
	
	/**
	 * 出入库流水明细
	 * @param id
	 * @return
	 */
	@RequestMapping("/queryInventoryInout")
	@ResponseBody
	public Object queryInventoryInout(InventoryQueryVO inventoryQueryVO) {
		JsonPageResult<List<InventoryInoutVO>> result = new JsonPageResult<>();
		ShiroUser one = this.getShiroUser();
		inventoryQueryVO.setCompanyId(one.getCompanyId());
		Set<String> roles = one.getRoles();
		if(roles.contains("irhbuyer")) {
			inventoryQueryVO.setUserCreate(one.getLoginName());
		}

		try {
			Integer count =  inventoryInoutService.queryInventoryInoutCount(inventoryQueryVO);
			if(count!=null&&count!=0L){
				result.buildPage(count, inventoryQueryVO);
				List<InventoryInoutVO> inventoryInoutVOS = inventoryInoutService.queryInventoryInouts(inventoryQueryVO);
				if(CollectionUtils.isNotEmpty(inventoryInoutVOS)){
					inventoryInoutVOS.forEach(inout->
					inout.setWarehouseName(warehouseService.getWarehouseById(inout.getWarehouseId()))
							);
					/*
					for (InventoryInoutVO inventoryInoutVO : inventoryInoutVOS) {
						if(inventoryInoutVO.getOperatorType()==2 || inventoryInoutVO.getOperatorType()==6) {
							EntityWrapper<PurchaseStorageDetail> PurchaseStorageDetailOne = new EntityWrapper<>();
							PurchaseStorageDetailOne.where("inventory_area_id={0} and online_number is not null", inventoryInoutVO.getInventoryAreaId());
							PurchaseStorageDetail stroList = purchaseStorageDetailService.selectOne(PurchaseStorageDetailOne);
							if(stroList != null ) {
								inventoryInoutVO.setOnlineNumber(stroList.getOnlineNumber());
							}
						}
					}
					*/
				}
				result.setData(inventoryInoutVOS);
			}
			result.buildIsSuccess(true);
		} catch (Exception e) {
			result.buildIsSuccess(false);
		}
		return result;
	}
	
	/**
	 * 导出excel
	 * @param id
	 */
	@RequestMapping("/inventoryAreaExport")
    public ResponseEntity<byte[]> inventoryAreaExport(InventoryQueryVO inventoryQueryVO) throws Exception {
    	List<List<Object>> rowDatas = new ArrayList<>();
    	List<InventoryArea> inventoryAreaList = inventoryAreaService.queryInventoryAreaForExcel(inventoryQueryVO);
    	if(inventoryAreaList != null) {
    		Double totalSalePrice = 0.0D;
    		for (InventoryArea inventoryArea : inventoryAreaList) {
    			List<Object> list = new ArrayList<>();
    			
    			list.add(inventoryArea.getSkuCode());		//SKU CODE
    			list.add(inventoryArea.getItemName());		//Item Name
    			//sku图片
    			String skuPic = inventoryArea.getSkuPic();
    			if(StringUtil.isNotBlank(skuPic)) {
    				PicModel pm = HaiJsonUtils.toBean(skuPic, PicModel.class);
        			String imgSrc = pm.getPicList().get(0).getUrl();
        			String imgType = imgSrc.substring(imgSrc.lastIndexOf(".") + 1).toUpperCase();
        			if(imgSrc.contains("aliyuncs.com")) {
        				imgSrc += "?x-oss-process=image/resize,m_lfit,h_100,w_100";
        			} else {
        				imgSrc = imgSrc.replaceAll("Resource", "Thumbnail");
        			}
        			//System.out.println(imgSrc);
        			URL url = new URL(imgSrc);
        			BufferedImage image = ImageIO.read(url);
        			ByteArrayOutputStream output = new ByteArrayOutputStream();
        	        ImageIO.write(image, imgType, output);
        	        output.flush();
        	        list.add(output.toByteArray());
        	        output.close();
    			} else {
    				list.add(null);
    			}
    			
    	        list.add(inventoryArea.getUpc());					//UPC
    	        list.add(inventoryArea.getBrand());					//品牌
    	        list.add(inventoryArea.getColor());					//颜色
    	        list.add(inventoryArea.getScale());					//尺码
    	        list.add(inventoryArea.getWarehouseName());			//仓库名称
    	        list.add(inventoryArea.getPositionNo());            //货架号
    	        list.add(inventoryArea.getTotalAvailableInv());		//可售库存
    	        list.add(inventoryArea.getInventory());				//现货库存
    	        list.add(inventoryArea.getLockedInv());				//现货占用
    	        list.add(inventoryArea.getTransInv());				//在途库存
    	        list.add(inventoryArea.getLockedTransInv());		//在途占用
    	        list.add(inventoryArea.getSalePrice());				//销售价格
    	        
    	        totalSalePrice += inventoryArea.getTotalAvailableInv()*inventoryArea.getSalePrice();
    			rowDatas.add(list);
    		}
    		List<Object> list = new ArrayList<>();
    		list.add("库存总金额：");
    		list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");list.add("");
    		list.add(totalSalePrice);
    		rowDatas.add(list);
    	}
    	ExcelHelper excelHelper = new ExcelHelper();
    	String[] columnTitles = new String[]{"SKU CODE", "商品名称", "商品图片", "UPC", "品牌", "颜色", "尺码", "仓库名称", "货架号", "可售库存", "现货库存", "现货占用", "在途库存", "在途占用", "销售价格"};
    	Integer[] columnWidth = new Integer[]{25, 30, 10, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15};
    	excelHelper.setInventoryAreaToSheet("inventoryArea", columnTitles, rowDatas, columnWidth);
    	//excelHelper.writeToFile("/Users/liuyang/Work/test.xls");
    	
    	ResponseEntity<byte[]> filebyte = null;
    	ByteArrayOutputStream  out = excelHelper.writeToByteArrayOutputStream();
    	HttpHeaders headers = new HttpHeaders();
    	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    	String fileName = "库存统计报表(" + DateUtil.formatDate(new Date(), "yyyyMMdd") + ").xlsx";
        headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("utf-8"), "ISO8859-1"));
        
        filebyte = new ResponseEntity<byte[]>(out.toByteArray(), headers, HttpStatus.OK);
        out.close();
        excelHelper.close();
        return filebyte;
    }
    
    /**
     * 修改货架号
     * @param inventoryAreaId
     * @param positionNo
     * @return
     */
    @RequestMapping("/changePositionNo")
	@ResponseBody
    public Object changePositionNo(Long inventoryAreaId, String positionNo) {
    	if(StringUtil.isBlank(positionNo)) {
    		return JsonResult.buildFailed("货架号不能为空！");
    	}
    	InventoryArea inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
    	if(inventoryArea.getLockedInv()>0) {
    		//如果有现货占用，先释放库存
    		EntityWrapper<ErpOrder> wrapper = new EntityWrapper<>();
			wrapper.where("sku_id={0} and status=0 and stock_status not in (0,9,7)", inventoryArea.getSkuId());
			List<ErpOrder> erpOrderList = erpOrderService.selectList(wrapper);
			if(erpOrderList.size() > 0) {
				for(int i=0; i<erpOrderList.size(); i++) {
					try {
						inventoryService.releaseInventory(erpOrderList.get(i));
					} catch (InventoryException e) {
						logger.error("orderId:"+erpOrderList.get(i).getId()+e.getMessage()+e);
						return JsonResult.buildFailed("操作失败，释放库存异常");
					}
				}
			}

			//释放库存后，更改货架号
			inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
			inventoryArea.setPositionNo(positionNo);
			inventoryAreaService.changePositionNo(inventoryArea);

			//重新分配库存
			if(erpOrderList.size() > 0) {
				erpOrderList.forEach(order->{
					try {
						erpOrderService.lockErpOrder(order);
					} catch (Exception e) {
						logger.info(e);
					}
				});
			}
    		//return JsonResult.buildFailed("此库存已有现货占用，不能更改货架号！");
			return JsonResult.buildSuccess(null);
    	} else {
    		inventoryArea.setPositionNo(positionNo);
    		inventoryAreaService.changePositionNo(inventoryArea);
    		return JsonResult.buildSuccess(null);
    	}
    }
    
   /**
    * 添加出库单
    *
    */
    @RequestMapping("/inventoryOutAdd")
	@ResponseBody
    public Object inventoryOutAdd(InventoryOut inventoryOut) {
    	JsonResult<String> result = new JsonResult<>();
		initInventoryOut(inventoryOut);
		inventoryOut.setStatus(GeneralStatus.INIT.getCode());
		
		inventoryOutService.addInventoryOut(inventoryOut);
		return result.buildIsSuccess(true);
    }
    
    /**
     * 查询单个出库单
     *
     */
    @RequestMapping("/inventoryOutQuery")
    @ResponseBody
    public Object inventoryOutQuery(Long id) {
   	 JsonResult<InventoryOut> result = new JsonResult<>();
   	 if (id != null) {
   		 InventoryOut inventoryOut = inventoryOutService.queryInventoryOut(id);
			if (inventoryOut == null) {
				result.buildIsSuccess(false).buildMsg("没有找到InventoryOut");
			}
			result.setData(inventoryOut);
			return result.buildIsSuccess(true);
		} else {
			return result.buildIsSuccess(false).buildMsg("没有Item id");
		}
    }
    
    /**
     * 修改出库单
     *
     */
    @RequestMapping("/inventoryOutUpdate")
 	@ResponseBody
	public Object inventoryOutUpdate(InventoryOut inventoryOut) {
     	JsonResult<String> result = new JsonResult<>();
     	if(inventoryOut.getId()==null) {
			return result.buildIsSuccess(false).buildMsg("没有ID");
		} else {
			InventoryOut io = inventoryOutService.selectById(inventoryOut.getId());
			if(io==null || io.getStatus()!=GeneralStatus.INIT.getCode()) {
				return result.buildIsSuccess(false).buildMsg("状态不对");
			}
		}
     	initInventoryOut(inventoryOut);
     	inventoryOut.setStatus(GeneralStatus.INIT.getCode());
 		inventoryOutService.updateInventoryOut(inventoryOut);
 		return result.buildIsSuccess(true);
     }
    
    public void initInventoryOut(InventoryOut inventoryOut) {
    	ShiroUser su = null;
		try {
			 su = this.getShiroUser();
		} catch (Exception e) {
			throw new ErpCommonException("没有登入");
		}
		final Long loginId = su.getId();
		final String loginName = su.getName();
		Date nowDate = new Date();
		
		if(inventoryOut.getId() == null) {	//新增
			//出库单号
			String invOutNo = "IOUT" + DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD) + "U" + String.format("%0"+4+"d", loginId) + sequenceUtilService.gainINVOUTSequence();
			inventoryOut.setInvOutNo(invOutNo);
			inventoryOut.setUserCreate(loginName);
			inventoryOut.setGmtCreate(nowDate);
			inventoryOut.setGmtModify(nowDate);
		} else {
			inventoryOut.setUserModify(loginName);
	 		inventoryOut.setGmtModify(nowDate);
		}
		
    	if(!StringUtils.isEmpty(inventoryOut.getInventoryOutDetailListStr())) {
			String s = inventoryOut.getInventoryOutDetailListStr().replace("&quot;", "\"");
			List<InventoryOutDetail> details = HaiJsonUtils.toBean(s, new TypeReference<List<InventoryOutDetail>>(){});
			details.forEach(
					detail -> {
							if(detail.getInventoryAreaId()==null || detail.getQuantity()==null || detail.getQuantity()<=0) {
								throw new ErpCommonException("参数异常");
							}
							InventoryArea inventoryArea= inventoryAreaService.selectById(detail.getInventoryAreaId());
							detail.setItemId(inventoryArea.getItemId());
							detail.setSkuId(inventoryArea.getSkuId());
							detail.setItemName(inventoryArea.getItemName());
							detail.setScale(inventoryArea.getScale());
							detail.setColor(inventoryArea.getColor());
							detail.setUpc(inventoryArea.getUpc());
							detail.setSkuCode(inventoryArea.getSkuCode());
							detail.setSkuPic(inventoryArea.getSkuPic());
							detail.setPositionNo(inventoryArea.getPositionNo());
							detail.setGmtCreate(nowDate);
							detail.setGmtModify(nowDate);
					}
			);
			inventoryOut.setInventoryOutDetailList(details);
		}
    }
     
	/**
	 * 查询出库单列表
	 *
	 */
	@RequestMapping("/inventoryOutQueryList")
  	@ResponseBody
  	public Object inventoryOutQueryList(InventoryOutVO inventoryOutVO) {
		JsonPageResult<List<InventoryOut>> result = new JsonPageResult<>();
		try{
			result = inventoryOutService.inventoryOutQueryList(inventoryOutVO);
			result.buildIsSuccess(true);
		}catch(Exception e){
			e.printStackTrace();
			result.buildIsSuccess(false);
		}
		return result;
	}
	
	/**
	 *确认出库,区分新增出库和修改出库，逻辑不同
	 * @param
	 * @return
	 */
	@RequestMapping("/inventoryOutConfirm")
	@ResponseBody
	public Object inventoryOutConfirm(InventoryOut inventoryOut) {
		JsonResult<String> result = new JsonResult<>();
		Set<Long> skuIdSet = null;
		if(inventoryOut.getId()==null) {	//新增出库
			initInventoryOut(inventoryOut);
			inventoryOut.setStatus(GeneralStatus.CONFIRM.getCode());
			skuIdSet = inventoryOutService.addInventoryOutConfirm(inventoryOut);
		} else {
			if(inventoryOut.getId()==null) {
				return result.buildIsSuccess(false).buildMsg("没有ID");
			} else {
				InventoryOut io = inventoryOutService.selectById(inventoryOut.getId());
				if(io==null || io.getStatus()!=GeneralStatus.INIT.getCode()) {
					return result.buildIsSuccess(false).buildMsg("状态不对");
				}
			}
	     	initInventoryOut(inventoryOut);
	     	inventoryOut.setStatus(GeneralStatus.CONFIRM.getCode());
	     	skuIdSet = inventoryOutService.updateInventoryOutConfirm(inventoryOut);
		}
		//对子订单进行库存分配
		if(skuIdSet!=null && !skuIdSet.isEmpty()) {
			for(Long skuId:skuIdSet) {
				try {
					erpOrderService.lockErpOrderBySkuId(skuId);
				} catch (InventoryException e) {
					logger.info("批量盘出-入库锁库存异常skuid:"+skuId, e);
				}
			}
		}
		return result.buildIsSuccess(true);
	}
	
	/**
	 *删除出库单
	 * @param
	 * @return
	 */
	@RequestMapping("/inventoryOutDelete")
	@ResponseBody
	public Object inventoryOutDelete(Long id){
		JsonResult<String> result = new JsonResult<>();
		
		try{
			inventoryOutService.deleteInventoryOutById(id);
			return result.buildIsSuccess(true);
		}catch(ErpCommonException e){
			return result.buildIsSuccess(false).buildMsg(e.getErrorMsg());
		}catch(Exception ex){
			return result.buildIsSuccess(false).buildMsg("未知异常");
		}
	}
	/**
	 * 备货商品列表查询
	 * @param inventoryQueryVO
	 * @return
	 */
	@RequestMapping("/stockWarehouse")
	@ResponseBody
	public Object querystockWarehouse(InventoryQueryVO inventoryQueryVO) {
		JsonPageResult<List<InventoryStock>> result = new JsonPageResult<>();
		try {
			if(StringUtil.isNotBlank(inventoryQueryVO.getOrderBy())) {
				String orderBy = Underline2Camel.camel2Underline(inventoryQueryVO.getOrderBy());
				inventoryQueryVO.setOrderBy(orderBy);
			}
			result = inventoryStockService.queryInventoryStock(inventoryQueryVO);
			result.buildIsSuccess(true);
		} catch (Exception e) {
			result.buildIsSuccess(false);
		}
		return result;
	}
	/**
	 * 盘出到备货仓
	 * @param inventoryAreaId
	 * @param quantity
	 * @return
	 * @throws InventoryException
	 */
	@RequestMapping("/inventoryCheckOuttoStock")
	@ResponseBody
	public Object inventoryCheckOuttoStock(Long inventoryAreaId, Integer quantity, String inoutReason) throws InventoryException {
		// 非空校验
		if (inventoryAreaId== null ||quantity == null) {
			return JsonResult.buildFailed("有空数据");
		}else{
			if (quantity <= 0) {
				return JsonResult.buildFailed("盘出的库存要为正数");
			}
			try {
				inventoryService.inventoryCheckOut(inventoryAreaId, quantity, inoutReason);
			}catch (InventoryException e) {
				this.logger.error(e);
				return JsonResult.buildFailed(e.getMessage());
			} catch (Exception ex) {
				this.logger.error(ex);
				return JsonResult.buildFailed("未知异常");
			}
			
			//对子订单进行库存分配
			InventoryArea inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
			try {
				erpOrderService.lockErpOrderBySkuId(inventoryArea.getSkuId());
			} catch (InventoryException e) {
				logger.info("库存盘出，子订单重新库存分配异常skuid:"+inventoryArea.getSkuId(), e);
			}
		}
		
		InventoryArea inventoryArea = inventoryAreaMapper.selectById(inventoryAreaId);
		
		InventoryStock tjInsetStock = new InventoryStock();
		tjInsetStock.setSkuId(inventoryArea.getSkuId());
		InventoryStock selInsetStock = inventoryStockService.selectOne(tjInsetStock);
		if(selInsetStock != null) {
			selInsetStock.setInventory(selInsetStock.getInventory() + quantity);
			selInsetStock.setGmtModify(new Date());
			inventoryStockService.updateSelectiveById(selInsetStock);
		} else {
			InventoryStock insetStock = new InventoryStock();
			BeanUtils.copyProperties(inventoryArea, insetStock);
			insetStock.setInventory(quantity);
			insetStock.setLockedInv(0);
			insetStock.setTransInv(0);
			insetStock.setLockedTransInv(0);
			insetStock.setGmtCreate(new Date());
			insetStock.setGmtModify(new Date());
			inventoryStockService.insertSelective(insetStock);
		}
		return JsonResult.buildSuccess(null);
	}
	/**
	 * 库存调整，库存盘进、盘出
	 * 
	 * @param orderId
	 * @return
	 * @throws InventoryException
	 */
	@RequestMapping("/inventoryStockCheckIn")
	@ResponseBody
	public Object inventoryStockCheckIn(Long skuId, Long warehouseId, String positionNo, Integer quantity,Long id,String inoutReason)
			throws InventoryException {
		InventoryStock insetStock = inventoryStockService.selectById(id);
		if(quantity > insetStock.getInventory()) {
			return JsonResult.buildFailed("存入库存数量超过国内仓现有数量");
		}
		
		// 非空校验
		if (skuId == null || warehouseId == null || StringUtils.isBlank(positionNo) || quantity == null) {
			return JsonResult.buildFailed("有空数据");
		} else {
			if (quantity <= 0) {
				return	JsonResult.buildFailed("增加库存要为正数");
			}
			try {
				inventoryAreaService.inventoryCheckIn(skuId, warehouseId, positionNo, quantity, inoutReason);
			} catch (ErpCommonException e) {
				this.logger.error(e);
				return JsonResult.buildFailed(e.getErrorMsg());
			} catch (Exception ex) {
				this.logger.error(ex);
				return JsonResult.buildFailed("未知异常");
			}
			try {
				//对子订单进行库存分配
				erpOrderService.lockErpOrderBySkuId(skuId);
			} catch (InventoryException e) {
				logger.info("库存盘进，子订单重新库存分配异常skuid:"+skuId, e);
			}

		}
		
		insetStock.setInventory(insetStock.getInventory()- quantity);
		inventoryStockService.updateSelectiveById(insetStock);
		return JsonResult.buildSuccess(null);
	}
	/**
	 * 盘出在途库存
	 * @param inventoryAreaId
	 * @param quantity
	 * @return
	 * @throws InventoryException
	 */
	@RequestMapping("/transInvCheckOut")
	@ResponseBody
	public Object transInvCheckOut(Long inventoryAreaId, Integer quantity,Long storagerDetailtId) throws InventoryException {
		// 非空校验
		if (inventoryAreaId== null ||quantity == null) {
			return JsonResult.buildFailed("有空数据");
		}else{
			if (quantity <= 0) {
				return JsonResult.buildFailed("减少的库存要为正数");
			}
			try {
				inventoryService.transInvCheckOut(inventoryAreaId, quantity, storagerDetailtId);
			}catch (InventoryException e) {
				this.logger.error(e);
				return JsonResult.buildFailed(e.getMessage());
			} catch (Exception ex) {
				this.logger.error(ex);
				return JsonResult.buildFailed("未知异常");
			}
			
			//对子订单进行库存分配
			InventoryArea inventoryArea = inventoryAreaService.selectById(inventoryAreaId);
			try {
				erpOrderService.lockErpOrderBySkuId(inventoryArea.getSkuId());
			} catch (InventoryException e) {
				logger.info("库存盘出，子订单重新库存分配异常skuid:"+inventoryArea.getSkuId(), e);
			}
		}
		return JsonResult.buildSuccess(null);
	}
	
	/**
	 * 出入库相关操作人员
	 */
	@RequestMapping("/queryCreaterList")
  	@ResponseBody
  	public Object queryCreaterList() {
		List<UserHai> users = userServiceHai.queryCreaterList();
		return JsonResult.buildSuccess(users);
	}
	
	@RequestMapping("/queryOnlineQuantity")
	@ResponseBody
	public Object fileDelete(Long id){
		JsonResult<PurchaseStorageDetail> result = new JsonResult<>();
		PurchaseStorageDetail one = purchaseStorageDetailMapper.selectById(id);
		return result.buildData(one).buildIsSuccess(true);
	}
}
